﻿using SharpDX.Direct3D9;
using SharpDX;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows;
using System.Windows.Controls;

namespace MyMeeting.src.Advanced.CustomRender
{
    public partial class TestRender : Window
    {
        private D3DImage _d3dImage;
        private Direct3D _d3d;
        private Device _device;
        private Texture _renderTarget;
        StackPanel D3DPanel;

        public TestRender()
        {
           
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeD3D();
            InitializeD3DImage();
            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }

        private void InitializeD3D()
        {
            // 创建 Direct3D 9 设备
            _d3d = new Direct3D();
            var presentParams = new PresentParameters
            {
                Windowed = true,
                SwapEffect = SwapEffect.Discard,
                DeviceWindowHandle = GetDesktopWindow(),
                PresentationInterval = PresentInterval.Default,
                BackBufferWidth = (int)D3DPanel.ActualWidth,
                BackBufferHeight = (int)D3DPanel.ActualHeight,
                BackBufferFormat = Format.X8R8G8B8
            };

            _device = new Device(_d3d, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, presentParams);

            // 创建渲染目标纹理
            _renderTarget = new Texture(_device, (int)D3DPanel.ActualWidth, (int)D3DPanel.ActualHeight, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default);
        }

        private void InitializeD3DImage()
        {
            // 创建 D3DImage
            _d3dImage = new D3DImage();
            _d3dImage.IsFrontBufferAvailableChanged += D3DImage_IsFrontBufferAvailableChanged;

            // 将 D3DImage 绑定到 Image 控件
            var image = new System.Windows.Controls.Image
            {
                Source = _d3dImage,
                Stretch = Stretch.None
            };

            // 将 Image 控件添加到 Panel 中
            D3DPanel.Children.Add(image);

            // 设置 D3DImage 的后缓冲区
            SetBackBuffer();
        }

        private void SetBackBuffer()
        {
            if (_d3dImage.IsFrontBufferAvailable && _renderTarget != null)
            {
                var surface = _renderTarget.GetSurfaceLevel(0);
                _d3dImage.Lock();
                _d3dImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                _d3dImage.Unlock();
            }
        }

        private void D3DImage_IsFrontBufferAvailableChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (_d3dImage.IsFrontBufferAvailable)
            {
                SetBackBuffer();
            }
        }

        private void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            Render();
        }

        private void Render()
        {
            if (_device == null || _renderTarget == null)
                return;

            // 清除渲染目标
            _device.SetRenderTarget(0, _renderTarget.GetSurfaceLevel(0));
           // _device.Clear(ClearFlags.Target, Color.FromArgb(0, 0, 1, 1), 1.0f, 0);

            // 开始渲染
            _device.BeginScene();

            // 在这里添加你的 Direct3D 渲染代码
            // 例如：绘制三角形、纹理等

            _device.EndScene();

            // 更新 D3DImage
            _d3dImage.Lock();
            _d3dImage.AddDirtyRect(new Int32Rect(0, 0, _d3dImage.PixelWidth, _d3dImage.PixelHeight));
            _d3dImage.Unlock();
        }

        private IntPtr GetDesktopWindow()
        {
            return System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
        }
    }
}
